package CloudStorageServlets;

import CloudStorage.*;
import CloudStorage.User;
import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckoutServlet extends HttpServlet
{
    public static void zipDownloads(ArrayList<CloudStorage.File> files) throws IOException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException
    {
        Database database = new Database();
        String zipFile = "cloudstoredownloads.zip";
        byte[] buffer = new byte[1024];
        FileOutputStream fout = new FileOutputStream(zipFile);
        ZipOutputStream zout = new ZipOutputStream(fout);

	for(int i=0; i < files.size(); i++)
        {
            String uploader = database.getUsername(files.get(i).getOwnerId());
            FileInputStream fin = new FileInputStream(uploader + "/" + files.get(i).getFullName());

            zout.putNextEntry(new ZipEntry(files.get(i).getName()));
            int length;
            while((length = fin.read(buffer)) > 0)
            {
                zout.write(buffer, 0, length);
            }

            zout.closeEntry();
            fin.close();
        }

        zout.close();
  }
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, IOException
    {
        HttpSession session = request.getSession();

        if ( request.getParameter("cancel") != null )
        {
            session.removeAttribute("amount");
            session.removeAttribute("final step");
            response.sendRedirect("index.jsp");
            return;
        }

        if ( session.getAttribute("user") == null && session.getAttribute("final step") == null )
        {
            session.setAttribute("final step", "");
            response.sendRedirect("checkout.jsp");
            return;
        }

        Cart cart = (Cart) session.getAttribute("cart");

        if ( session.getAttribute("user") != null )
        {
            Database database = new Database();
            User user = (User) session.getAttribute("user");

            float amount = Float.parseFloat( request.getParameter("amount") );
            
//            database.chargeUser(user, amount);

            for ( CloudStorage.File file : cart.getFiles() )
            {
                database.payUser(file.getOwnerId(), file.getValue());
            }

            for ( CloudStorage.File file : cart.getFiles() )
            {
                database.updateDownloadCounter(file.getID());
            }

            database.deleteCart(cart);
        }

        zipDownloads(cart.getFiles());

        ServletOutputStream out = response.getOutputStream();

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition","attachment; filename=cloudstoredownloads.zip" );
        java.io.File file = new java.io.File("cloudstoredownloads.zip");

        FileInputStream fileIn = new FileInputStream(file);

        byte[] outputByte = new byte[4096];

        while(fileIn.read(outputByte, 0, 4096) != -1)
        {
            out.write(outputByte, 0, 4096);
        }

        fileIn.close();
        out.flush();
        out.close();
        
        session.removeAttribute("cart");
        session.setAttribute("cart", new Cart());
        session.removeAttribute("final step");
        response.sendRedirect("index.jsp");
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(CheckoutServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(CheckoutServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(CheckoutServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(CheckoutServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(CheckoutServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(CheckoutServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(CheckoutServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(CheckoutServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
